package com.zsc.shixun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.shixun.common.ResultCode;
import com.zsc.shixun.contant.Contant;
import com.zsc.shixun.controller.WebSocketServer;
import com.zsc.shixun.entity.Article;
import com.zsc.shixun.entity.Comment;
import com.zsc.shixun.entity.User;
import com.zsc.shixun.exception.ApiException;
import com.zsc.shixun.mapper.CommentMapper;
import com.zsc.shixun.model.article.ArticleVO;
import com.zsc.shixun.model.comment.CommentCreateVO;
import com.zsc.shixun.model.comment.CommentVO;
import com.zsc.shixun.model.comment.CommmentMapping;
import com.zsc.shixun.service.IArticleService;
import com.zsc.shixun.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.shixun.service.IMessageService;
import com.zsc.shixun.utils.LoginMessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author ZWYZY
 * @since 2020-06-06
 */
@Service
@Transactional
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    private static final Logger logger = LoggerFactory.getLogger(CommentServiceImpl.class);

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private CommmentMapping commmentMapping;

    @Autowired
    private IMessageService messageService;
    @Autowired
    private LoginMessageUtils loginMessageUtils;
    @Override
    public List<CommentVO> getData(Long id) {
        if (redisTemplate.hasKey(Contant.COMMENT_KEY + id)) {
            return (List<CommentVO>) redisTemplate.opsForValue().get(Contant.COMMENT_KEY + id);
        }
        List<ArticleVO> articleVOList = articleService.getData(id);
        List<CommentVO> commentVOList = new ArrayList<>(10);
        articleVOList.forEach(articleVO ->
            commentVOList.addAll(commmentMapping.entitysToVos(this.list(new QueryWrapper<Comment>().lambda().eq(Comment::getArticleId, articleVO.getId()))))
        );

        return commentVOList;
    }

    @Override
    public void delete(Long id) {
        Comment comment = this.getById(id);
        Article article = new Article();
        article.setId(comment.getArticleId());
        article.setCommentNumber(articleService.getById(comment.getArticleId()).getCommentNumber() - 1);
        try {
            articleService.updateById(article);
            this.removeById(id);
        } catch (Exception e) {
            logger.error("删除评论失败");
            throw new ApiException(ResultCode.COMMENT_DELETE_FAIL);
        }
        logger.info("删除评论成功");
        if (redisTemplate.hasKey(Contant.COMMENT_KEY + comment.getUserId())) {
            redisTemplate.delete(Contant.COMMENT_KEY + comment.getUserId());
        }

    }

    @Override
    public void insert(CommentCreateVO commentCreateVO) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentCreateVO, comment);
        this.save(comment);
        logger.info("评论成功");
        Article article = articleService.getById(comment.getArticleId());
        article.setCommentNumber(article.getCommentNumber() + 1);
        articleService.updateById(article);

        if (redisTemplate.hasKey(Contant.COMMENT_KEY + comment.getUserId())) {
            redisTemplate.delete(Contant.COMMENT_KEY + comment.getUserId());
        }
        if (redisTemplate.hasKey(Contant.ARTICLE_KEY + comment.getUserId())) {
            redisTemplate.delete(Contant.ARTICLE_KEY + comment.getUserId());
        }
        if (redisTemplate.hasKey(Contant.DATA_ADMIN_KEY)) {
            redisTemplate.delete(Contant.DATA_ADMIN_KEY);
        }
        if (redisTemplate.hasKey(Contant.DATA_COMMON_KEY + comment.getUserId())) ;
        {
            redisTemplate.delete(Contant.DATA_COMMON_KEY + comment.getUserId());
        }


        String message="博主名为"+loginMessageUtils.getMessage().getLoginUser().getUsername()+"的用户评论了你";
        try {
            WebSocketServer.sendObjToUser(messageService.insertMessage(commentCreateVO.getUserId(),loginMessageUtils.getMessage().getLoginUser().getId(),message),commentCreateVO.getUserId());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
